package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	resp "study/server/model/response"
	"study/server/service/redis_service/token_black"
	"study/server/utils/my_jwt"
)

func CheckTokenWhetherBlack() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取token
		token := c.Request.Header.Get("token")
		fmt.Println(token)
		claims, err := my_jwt.ParseToken(token)
		if token == "" || err != nil {
			resp.FailWithMsg("未登录", c)
			c.Abort()
			return
		}
		// 判断是否在黑名单中
		if token_black.CheckTokenBlack(token) {
			resp.FailWithMsg("该用户已注销", c)
			c.Abort()
			return
		}
		// 将claims中的信息存储到上下文
		c.Set("claims", claims)
		// 继续处理请求
		c.Next()
	}
}

func GetTokenFromContext(c *gin.Context) *my_jwt.CustomClaims {
	// 从上下文获取claims
	return c.MustGet("claims").(*my_jwt.CustomClaims)
}
